package com.kuizii.base.api;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * feign错误处理
 */
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {

        String url = "";
        if (response != null && response.request() != null) {
            url = response.request().url();
        }
        try {
            // 这里直接拿到我们抛出的异常信息
            String message = Util.toString(response.body().asReader(Charset.defaultCharset()));

            String reqBody = "";
            if (response.request().body() != null) {
                reqBody = response.request().toString();
            }
            log.error(String.format("feign throw exception====>> url:%s   method:%s  \r\n questBody %s   \r\n reason:%s", url, methodKey, reqBody, message));
            if (response.status() == 404) {
                return new FeignResponseException("调用的地址不存在", response.status(), url);
            }
            JSONObject jsonObject = JSONObject.parseObject(message);
            FeignResponseException exception=  new FeignResponseException(jsonObject.getString("message"), response.status(), url);
            exception.setDetailMsg(jsonObject.getString("detailMsg"));
            exception.setErrorCode(jsonObject.getInteger("errorCode"));
            exception.setCause(jsonObject.getObject("cause",Throwable.class));
            exception.setData(jsonObject.get("data"));
            return exception;
        } catch (JSONException e) {
            log.error(e.toString());
            return new FeignResponseException("json序列化异常", response.status(), url);
        } catch (IOException ignored) {
            log.error("IO异常,原因：" + ignored);
        }
        return new FeignResponseException("未知异常", response.status(), url);
    }
}